<template>
  <view>
      <view class="top-title" :style="{height:customBar+'px',paddingTop:statusBar+'px'}">
        <navigator
          url="../home/home"
          open-type="redirect"
          hover-class="none"
          class="top-title-back"
        >
          <image src="../../image/back2.png" style="margin-top:6rpx"/>
        </navigator>
        <text class="top-title-t1" style="text-align:center;width:80%">领用优惠券</text>
      </view>
      <!--优惠券可用-->
      <view v-if="status==1">
        <view class="bg"></view>
        <view class="coupon">
          <image src="../../image/counpon.png" />
          <view class="coupon-content">
            <view class="p1">
             {{couponInfos.shopCoupon.couponName}}
            </view>
            <view class="p1" style="font-size: 28rpx;font-weight: 500;">临停车优惠券</view>
            <view class="p2" v-if="couponInfos.shopCoupon.isFixPrice">有效期{{couponInfos.shopCoupon.validDays}}天</view>
            <view class="p2" style="text-align:right">由{{couponInfos.shop.shopName}}提供</view>
          </view>
        </view>
        <view class="bgBox"></view>
        <view class="bgwhite">
          <view class="item" v-if="couponInfos.shopCoupon.couponType==2">
            <text>可减免</text>
            <text>可减免{{couponInfos.shopCoupon.hourAllowance}}小时</text>
          </view>
          <view class="item" v-if="couponInfos.shopCoupon.validityType==1">
            <text>有效时间</text>
            <text>自领取时起{{couponInfos.shopCoupon.validDays}}天内有效</text>
          </view>
          <view class="item" v-if="couponInfos.shopCoupon.validityType==2">
            <text>截止日期</text>
            <text>{{couponInfos.shopCoupon.absoluteEndDate}}</text>
          </view>
          <view class="item" v-if="couponInfos.shopCoupon.couponType==1">
            <text>代金券</text>
            <text>至多抵扣{{couponInfos.shopCoupon.deduction}}元</text>
          </view>
          <view class="item">
            <text>品类限制</text>
            <text>仅限临时停车费用抵扣</text>
          </view>
          <view class="item">
            <text>适用停车场</text>
          </view>
          <view class="scroll" v-if="parkList.length>0">
            <view class="park-item" v-for="(item,index) in parkList" :key="index">
              <image src="../../image/icon1.png" class="park-item-img" />
              <view>
                <view class="park-p1">{{item.parkName}}</view>
                <view class="park-p2" v-if="item.remark">{{item.remark}}</view>
                <view class="park-p2" v-else>暂无地址信息</view>
              </view>
            </view>
          </view>
          <view v-else style="text-align:center;padding-top:30px;color:#666">暂无可用车场</view>
          <view class="btn" @tap="sureReceive">领取</view>
        </view>
      </view>
      <!--暂无优惠券-->
      <view v-if="status==0">
      <view class="empty">
        <image src="../../image/empty6.png" class="empty-img"/>
        <view class="empty-p1">{{errorMsg}}</view>
        <view class="btn" @tap="goHome">确定</view>
      </view>
      </view>
      <!--获取手机号-->
      <view v-if="!hasPhone">
      <view class="panel-black"></view>
      <view class="panel-box">
        <view class="panel-box-t1">提示</view>
        <view class="panel-box-t2">尚未获取手机号，无法领取优惠券</view>
        <button
          openType="getPhoneNumber"
          @GetPhoneNumber="onGetPhoneNumber"
          class="panel-box-btn"
          style="height:100rpx"
        >获取手机号</button>
      </view>
    </view>
  </view>
</template>
<script>
import Taro from "@tarojs/taro";
import { setGlobalData, getGlobalData } from "../../globalData.js";
import authorize from "../../authorize.js";
import "./receiveCounpon.less";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
// pages/card/card.js
export default {
  data() {
    return {
      apiBaseUrl: process.env.IOParking.API_HOST, //请求头
      id:null,//优惠券详情id
      couponInfos:null,
      hasPhone: true,
      parkList:null,//适用车场
      status:null,
      errorMsg:'',
      statusBar: 0,//状态栏高度
      customBar:0,//胶囊按钮高度
    };
  },
  mixins: [authorize],
  mounted(){
    Taro.getSystemInfo({
      success:(res)=> {
        this.statusBar = res.statusBarHeight; //状态栏高度
        let custom = Taro.getMenuButtonBoundingClientRect(); //菜单按钮
        this.customBar = custom.height+8;
        console.log(this.statusBar,this.customBar);
      }
    });
  },
  onLoad: function(options) {
    console.log(options,'用户信息',getGlobalData("openId"),getGlobalData("mobile"));
    var that=this
   if (options.id) {
      //体验开发版本扫码获得参数
      that.id = options.id ? options.id : "";
    } else if (options.q) {
      //正式版扫码获得参数
      let qrUrl = decodeURIComponent(options.q);
      that.id = that.getQueryString(qrUrl, "id");
    }
    if (!getGlobalData("openId")) {
      that.wx_login();
    }else{
      that.initData();
    }
  },
 
  methods: {
    initData(){
      console.log("获取优惠券信息")
      Taro.showLoading({
        title: "加载中",
        mask: true
      });
      var that = this;
      var base = that.apiBaseUrl;
      Taro.request({
        url: base + "/shopcoupon/shopcoupondetail",
        data: {
            mobile: getGlobalData("mobile")?getGlobalData("mobile"):'',
            openId: getGlobalData("openId"),
            id: that.id
        },
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "POST",
        success(res) {
          Taro.hideLoading();
          that.loading = false;
          console.log(res.data)
          if (res.data.isSuccess) {
            that.status=1
           that.couponInfos=res.data.data
           that.parkList=res.data.data.shopCoupon.parkList
          }else{
            that.status=0
            that.errorMsg=res.data.message
          }
        }
      });
    },
    sureReceive(){
      var that = this;
      if(getGlobalData("mobile")==''||!getGlobalData("mobile")){
        that.hasPhone=false
        return
      }
      var base = that.apiBaseUrl;
      Taro.showLoading({
        title: "领取中",
        mask: true
      });
      Taro.request({
        url: base + "/shopcoupon/receiveshopcoupon",
        data: {
            mobile: getGlobalData("mobile"),
            openId: getGlobalData("openId"),
            id: that.id,
            nickName:'',
        },
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "POST",
        success(res) {
          Taro.hideLoading();
          that.loading = false;
          console.log(res.data)
          if (res.data.isSuccess) {
            Taro.redirectTo({
                    url: "../counpon/receiveSuccess"
              });
          }else{
            that.status=0
            that.errorMsg=res.data.message
          }
        }
      });
    },
    goHome(){
       api.openPage("home");
    },
     //解析链接方法
    getQueryString(url, name) {
      var reg = new RegExp("(^|&|/?)" + name + "=([^&|/?]*)(&|/?|$)", "i");
      var r = url.substr(1).match(reg);
      if (r != null) {
        return r[2];
      }
      return null;
    },
    wx_login() {
      api
        .getUserInfo({
          scope: "all"
        })
        .then(resp => {
          if (resp.success) {
            console.log("authCode is：", resp.data);
            if (resp.data == "mock") {
              setGlobalData("openId", "oRPxj5ZrsZGRuxTa-UrzEBeLuv-s");
              //setGlobalData("mobile", "17761643218");
              this.initData();
              return;
            }
            this.getInfos(resp.data);
          } else {
            console.log("err is ", resp.message, "err code is ", resp.code);
          }
        });
    },
   getInfos(authCode) {
      let that = this;
      Taro.showLoading({
        title: "正在读取信息",
        mask: true
      });
      Taro.request({
        url: that.apiBaseUrl + "/weixin/souchegetuser?authCode=" + authCode,
        data: {},
        header: {
          "content-type": "application/json" // 默认值
        },
        method: "GET",
        success(res) {
          Taro.hideLoading();
          if (res.data.isSuccess) {
            var userOpenId = res.data.data.openId;
            setGlobalData("openId", userOpenId);
            setGlobalData("mobile", res.data.data.phoneNum);
            console.log(getGlobalData("openId"),getGlobalData("mobile"));
            that.initData();
            if(res.data.data.phoneNum!==''){
              that.hasPhone=true
             }else{
               console.log("没有手机号信息")
               //that.hasPhone=false
             }
          }
        }
      });
    },
   onGetPhoneNumber({ detail }) {
            const { encryptedData, iv } = detail;
            console.log("phone打印:" + JSON.stringify(detail));
            if (encryptedData && iv) {
              this.authPhone(encryptedData, iv);
              Taro.showLoading({
                  title: "授权中，请稍后",
                  mask: true
                });
            }
          },
  authPhone(encryptedData,iv) {
        api.register({
                encryptedData: encryptedData,
                iv: iv,
                scope: "all"
            })
            .then(resp => {
                Taro.hideLoading();
                if (resp.success) {
                    console.log("用户注册 ", resp.data);
                    if(resp.data=='mock'){
                        setGlobalData("mobile", '17761643218');
                          this.mobile=getGlobalData("mobile")?getGlobalData("mobile"):"";
                        return
                    }
                    this.getInfos(resp.data)
                } else {
                    console.log("err is ", resp.msg, "err code is ", resp.code);
                }
            })
            .catch(e => {
                console.log(e);
            });
    },
  }
};
</script>
